package com.eningqu.aipen.ui.medical;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.eningqu.aipen.MyApplication;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.databinding.ActivityPatientBinding;
import com.eningqu.aipen.logic.model.medical.MedicalBookBean;
import com.eningqu.aipen.logic.model.medical.MedicalNodeWithXyModelBean;
import com.eningqu.aipen.logic.model.medical.MedicalNodeWithZyModelBean;
import com.eningqu.aipen.logic.network.Apis;
import com.eningqu.aipen.logic.network.BaseRetrofitUtils;
import com.eningqu.aipen.logic.network.SchedulerTransformer;
import com.eningqu.aipen.ui.adapter.MedicalNodeAdapter;
import com.eningqu.aipen.ui.adapter.MedicalZyNodeAdapter;
import com.eningqu.aipen.ui.base.BaseActivity;
import com.eningqu.aipen.ui.dialog.LoadingAlertDialog;
import com.eningqu.aipen.ui.home.book.WriteActivity;
import com.eningqu.aipen.utils.GlideUtils;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.luck.picture.lib.utils.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Package:com.eningqu.aipen.ui.medical
 * Author:starr
 * Time:2023/11/16 14:10
 * Description: 患者病历详细信息
 */
public class MedicalNodeActivity extends BaseActivity<ActivityPatientBinding> {


    private RecyclerView recyclerView;
    private MedicalNodeAdapter adapter;
    private MedicalZyNodeAdapter zyNodeAdapter;

    private LoadingAlertDialog loadingDialog;
    private boolean isXySelect = true;
    private SmartRefreshLayout smartRefresh;
    private boolean isOpen = false;
    private String infos;
    private final List<MedicalNodeWithXyModelBean.JdListDTO> list = new ArrayList<>();
    private final List<MedicalNodeWithZyModelBean.JdListDTO> zyList = new ArrayList<>();

    private static int blId = 0;
    private static MedicalBookBean.PageDTO patient;
    private final Handler handler = new Handler();

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, MedicalNodeActivity.class);
        blId = bundle.getInt("blId");
        patient = (MedicalBookBean.PageDTO) bundle.getSerializable("blhz");
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_patient;
    }

    @Override
    protected void initView() {

        loadingDialog = new LoadingAlertDialog(getContext());

        mBinding.titleTopBar.baseTvTitle.setText("病历详情");
        mBinding.titleTopBar.baseIvBack.setVisibility(View.VISIBLE);
        mBinding.titleTopBar.baseIvBack.setOnClickListener(v -> finish());

        mBinding.setClick(new PatientClick());
        recyclerView = mBinding.rvPatientMedical;
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setStackFromEnd(true);
        layoutManager.setReverseLayout(true);
        recyclerView.setLayoutManager(layoutManager);
        mBinding.tvPatientName.setText(patient.hzInfoEntity.emrHzName);
        mBinding.tvMarry.setText(patient.hzInfoEntity.emrHzMarry);
        if (patient.hzInfoEntity.emrHzSex.equals("男")) {
            Glide.with(getContext()).load(R.drawable.ic_boy).into(mBinding.ivSex);
        } else {
            Glide.with(getContext()).load(R.drawable.ic_girl).into(mBinding.ivSex);
        }
        infos =  "出生日期：" + patient.hzInfoEntity.emrHzBirth;

        mBinding.tvInfo.setText(infos);
        GlideUtils.loadCircleImage(getContext(),patient.hzInfoEntity.emrHzImg,mBinding.ivPatientImg);
        smartRefresh = mBinding.smartRefresh;
        smartRefresh.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh(2000);
            async();
        });
        mBinding.clTabChange.setOnClickListener(v -> {
            if(isXySelect){
                mBinding.tvTabXy.setBackgroundResource(R.drawable.corner_gray_30);
                mBinding.tvTabZy.setBackgroundResource(R.drawable.corner_select_30);
            }else{
                mBinding.tvTabXy.setBackgroundResource(R.drawable.corner_select_30);
                mBinding.tvTabZy.setBackgroundResource(R.drawable.corner_gray_30);
            }
            isXySelect = !isXySelect;
            async();
        });
    }

    @Override
    protected void initData() {
        adapter = new MedicalNodeAdapter(list,patient);
        zyNodeAdapter = new MedicalZyNodeAdapter(zyList,patient);
    }

    @SuppressLint("CheckResult")
    @Override
    public void async() {
        loadingDialog.show();
        if(isXySelect){
            BaseRetrofitUtils.getInstance().create(Apis.class).getMedicalXyNodeById(blId)
                    .compose(new SchedulerTransformer<>())
                    .subscribe(bean -> {
                        loadingDialog.dismiss();
                        list.clear();
                        list.addAll(bean.jdList);
                        adapter.notifyDataSetChanged();
                        if (list.size() == 0) {
                            PopTip.tip("暂无数据");
                            mBinding.ivEmpty.setVisibility(View.VISIBLE);
                        } else {
                            mBinding.ivEmpty.setVisibility(View.GONE);
                            PopTip.tip("获取西医病程数据成功");
                        }
                    });
            recyclerView.setAdapter(adapter);
        }else{
            BaseRetrofitUtils.getInstance().create(Apis.class).getMedicalZyNodeById(blId)
                    .compose(new SchedulerTransformer<>())
                    .subscribe(bean -> {
                        loadingDialog.dismiss();
                        zyList.clear();
                        zyList.addAll(bean.jdList);
                        zyNodeAdapter.notifyDataSetChanged();
                        if (zyList.size() == 0) {
                            PopTip.tip("暂无数据");
                            mBinding.ivEmpty.setVisibility(View.VISIBLE);
                        } else {
                            mBinding.ivEmpty.setVisibility(View.GONE);
                            PopTip.tip("获取中医病程数据成功");
                        }
                    });
            recyclerView.setAdapter(zyNodeAdapter);
        }


    }


    @SuppressWarnings("all")
    public class PatientClick {

        public void back(View view) {
            finish();
        }

        public void moreInfo(View view){
            if(isOpen){
                infos="出生日期：" + patient.hzInfoEntity.emrHzBirth;
            }else{
                infos="出生日期：" + patient.hzInfoEntity.emrHzBirth+"\n"+
                "出生地："+patient.hzInfoEntity.emrHzPlace+"\n"+
                "职业："+patient.hzInfoEntity.emrHzJob+"\n"+
                "联系电话："+patient.hzInfoEntity.emrHzPhone;
            }
            mBinding.tvInfo.setText(infos);
            isOpen=!isOpen;

        }


        public void chooseModel(View view) {
            //检测蓝牙笔是否连接
            if (MyApplication.isConnect == -1) {
                PopTip.tip("请先连接智能点阵笔...");
                handler.postDelayed(() -> {
                    finish();
                }, 1000);
            } else {
                //选择病历模板
                BottomMenu.show(new String[]{"西医病历本(支持手写笔)", "中医病历本(支持手写笔)", "临床记录", "手术记录"})
                        .setMessage("请选择病历模板")
                        .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                            @Override
                            public boolean onClick(BottomMenu bottomMenu, CharSequence charSequence, int i) {
                                if(i>=2){
                                    ToastUtils.showToast(getContext(), charSequence.toString() + "  " + i);
                                }else{
                                    //跳转到书写界面
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("blId", blId);
                                    bundle.putInt("blModel", i);
                                    bundle.putInt("hzId",patient.emrHzId);
                                    WriteActivity.startAction(getContext(), bundle);
                                }
                                return false;
                            }
                        });

            }
        }
    }
}
